package com.pmcc.yn.service;

import com.pmcc.utils.AntdPage;
import com.pmcc.utils.BeanUtils;
import com.pmcc.utils.DateUtil;
import com.pmcc.utils.ResultBean;
import com.pmcc.yn.entity.*;
import com.pmcc.yn.repository.*;
import com.pmcc.yn.vo.EvaluateInfoVo;
import com.pmcc.yn.vo.MessageVo;
import com.pmcc.yn.vo.TechInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

/**
 * Created by shengxiaojing on 2019/1/11.
 */
@Service
@Transactional
public class TechnicianInfoService {

    @Autowired
    TechnicianInfoRepository repository;
    @Autowired
    AcceptInfoRepository acceptInfoRepository;
    @Autowired
    OrderListRepository orderListRepository;
    @Autowired
    EntryInfoRepository entryInfoRepository;
    @Autowired
    EvaluateInfoRepository evaluateInfoRepository;
    @Autowired
    StoreInfoRepository storeInfoRepository;
    @Autowired
    AttentionInfoRepository attentionInfoRepository;

    public ResultBean showList(AntdPage antdPage, TechnicianInfo model) throws Exception {
        ResultBean resultBean = new ResultBean();
        Page page = repository.findAll(this.getSpecification(model), antdPage.getPageRequest());

        resultBean.setPage(antdPage.getDefaultCurrent());
        resultBean.setTotal(page.getTotalElements());
        resultBean.setResultCode(ResultBean.SUCCESS);
        resultBean.setPageSize(antdPage.getPageSize());
        resultBean.setRows(page.getContent());
        return resultBean;
    }

    public Specification<TechnicianInfo> getSpecification(TechnicianInfo model) {
        return new Specification<TechnicianInfo>() {
            @Override
            public Predicate toPredicate(Root<TechnicianInfo> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if (model.getDelFlag() != null) {
                    list.add(builder.equal(root.get("delFlag").as(Integer.class), model.getDelFlag()));
                }

                Predicate[] p = new Predicate[list.size()];
                return builder.and(list.toArray(p));
            }
        };
    }

    /**
     * 新增
     *
     * @return
     */
    public ResultBean add(TechnicianInfo model) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            model.setCreateTime(new Date());
            model.setDelFlag(0);
//            model.setFlag(0);
            repository.saveAndFlush(model);
            resultBean.setObject(model);
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setResultDesc("新增成功");
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }


    /**
     * 修改
     *
     * @param map
     * @return
     */
    public ResultBean update(Map map) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            TechnicianInfo c = repository.findById(map.get("id").toString());
            BeanUtils.setBeanData(c, map);
            repository.saveAndFlush(c);
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setObject(c);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    public ResultBean deleteById(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            TechnicianInfo f = repository.findById(id);
            f.setDelFlag(1);
            repository.saveAndFlush(f);
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setObject(f);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }


    public ResultBean jslogin(String wxid) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            TechnicianInfo f = repository.findByWxId(wxid);
            if (f == null) {
                TechnicianInfo technicianInfo = new TechnicianInfo();
                // technicianInfo.setWxid(wxid);
                repository.saveAndFlush(technicianInfo);
                resultBean.setObject(technicianInfo);
            } else {
                resultBean.setObject(f);
            }
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    //门店登录
    public ResultBean login(String wxid) {
        ResultBean resultDesc = new ResultBean(ResultBean.SUCCESS);
        try {
            TechnicianInfo f = repository.findByWxId(wxid);
            if (f == null) {
                TechnicianInfo technicianInfo = new TechnicianInfo();
                technicianInfo.setWxId(wxid);
                repository.saveAndFlush(technicianInfo);
                resultDesc.setObject(technicianInfo);
            }

        } catch (Exception e) {
            resultDesc.setResultCode(ResultBean.FAIL);
        }
        return resultDesc;
    }

    /*
     * 报名技师列表
     *
     * */
    public ResultBean entryList(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            List<EntryInfo> entryInfo = entryInfoRepository.findByOrderId(id);
            List<TechInfoVo> list = new ArrayList<>();
            TechInfoVo techInfoVo = new TechInfoVo();
            for (EntryInfo entryInfo1 : entryInfo) {
                TechnicianInfo technicianInfo = repository.findById(entryInfo1.getTechnicianId());
                techInfoVo.setInfoImageUrl(technicianInfo.getImageurl());
                techInfoVo.setName(technicianInfo.getName());
                List<AcceptInfo> acceptInfoList = acceptInfoRepository.findByTechId(technicianInfo.getId());
                techInfoVo.setOrderNum(acceptInfoList.size());
                techInfoVo.setSatisfaction(technicianInfo.getSatisfaction());
                techInfoVo.setGrade(technicianInfo.getLevel());
                list.add(techInfoVo);
            }
            resultBean.setRows(list);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;

    }

    /**
     * 查看技师信息
     * @param id 技师id
     * @return 返回技师头像、姓名、接单次数、满意度、技师等级、综合评分、历史评价列表
     */
    public ResultBean teachInfo(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            TechnicianInfo technicianInfo = repository.findById(id);
            TechInfoVo techInfoVo = new TechInfoVo();
            techInfoVo.setInfoImageUrl(technicianInfo.getImageurl());
            techInfoVo.setName(technicianInfo.getName());
            List<AcceptInfo> acceptInfoList = acceptInfoRepository.findByTechId(technicianInfo.getId());
            techInfoVo.setOrderNum(acceptInfoList.size());
            techInfoVo.setSatisfaction(technicianInfo.getSatisfaction());
            techInfoVo.setGrade(technicianInfo.getLevel());
//            EvaluateInfoVo evaluateInfoVo = new EvaluateInfoVo();
            EvaluateInfo evaluateInfoList = evaluateInfoRepository.findById(id);
            List<EvaluateInfoVo> evaluateInfoVoList = new ArrayList<>();
//            for (EvaluateInfo evaluateInfo:evaluateInfoList){
//                EvaluateInfoVo evaluateInfoVo = new EvaluateInfoVo();
//                StoreInfo storeInfo = storeInfoRepository.findById(evaluateInfo.getEvaluatorId());
//                evaluateInfoVo.setStoreName(storeInfo.getName());
//                evaluateInfoVoList.add(evaluateInfoVo);
////                evaluateInfoVo.getScore();
////                evaluateInfoVo.getType();
////                evaluateInfoVo.getCommentContent();
////                evaluateInfoVo.getCommentImageUrl();
////                evaluateInfoVo.getCommentTime();
//            }
            techInfoVo.setEvaInfoVo(evaluateInfoVoList);
            resultBean.setObject(techInfoVo);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    //去评价
    public ResultBean storeAssess(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            EvaluateInfo evaluateInfo = evaluateInfoRepository.findByOrderId(id);
            TechInfoVo techInfoVo = new TechInfoVo();
            TechnicianInfo technicianInfo = repository.findById(evaluateInfo.getBeEvaluatorId());
            techInfoVo.setName(technicianInfo.getName());
            techInfoVo.setGrade(technicianInfo.getLevel());
            techInfoVo.setScore(technicianInfo.getScore());
            techInfoVo.setInfoImageUrl(technicianInfo.getImageurl());
            techInfoVo.setPhone(technicianInfo.getPhone());
            resultBean.setObject(techInfoVo);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    //门店报名关注状态详情
    public ResultBean statusShow(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            List<OrderList> orderList = orderListRepository.findByStoreId(id);
            TechInfoVo techInfoVo = new TechInfoVo();
            for (OrderList orderList1:orderList){
                TechnicianInfo technicianInfo = repository.findById(orderList1.getTechId());
                techInfoVo.setName(technicianInfo.getName());
                techInfoVo.setInfoImageUrl(technicianInfo.getImageurl());
                techInfoVo.setScore(technicianInfo.getScore());
                techInfoVo.setVeh_imageurl(orderList1.getVehPicl());
                techInfoVo.setSerType(orderList1.getSerType());
            }
            resultBean.setObject(techInfoVo);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean statusShowDetail(String id,String type) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {

            //查询出未删除和状态位等于1的该门店的订单信息
            List<OrderList> orderLists=orderListRepository.findByStoreIdAndDelFlagAndFlag(id,0,1);
            List<MessageVo> list=new ArrayList<>();
            if("0".equals(type)){
              //关注该门店的消息
                  for(OrderList order:orderLists){
                      List<AttentionInfo> attentionInfos=attentionInfoRepository.findByOrderIdOrderByAttentionTimeDesc(order.getId());
                       for(AttentionInfo ai:attentionInfos){
                           //获取技师的头像
                           TechnicianInfo technicianInfo=repository.findById(ai.getTechId());
                           String text="关注了"+order.getVehModel()+"的"+order.getSerType();
                           MessageVo mv=new MessageVo(ai.getTechId(),technicianInfo.getImageurl(),technicianInfo.getName(),technicianInfo.getScore()+"",order.getId(),order.getVehPicl(),text, ai.getAttentionTime());
                            list.add(mv);
                       }
                  }

            }else if("1".equals(type)){
                //报名该门店的消息

                for(OrderList order:orderLists){
                    List<EntryInfo> entryInfos=entryInfoRepository.findByOrderIdAndDelFlag(order.getId(),0);
                    for(EntryInfo ei:entryInfos){
                        //获取技师的头像
                        TechnicianInfo technicianInfo=repository.findById(ei.getTechnicianId());
                        String text="";
                        if(ei.getFlag()==0){
                            //报名了
                            text="报名了"+order.getVehModel()+"的"+order.getSerType();
                        }else if(ei.getFlag()==1){
                            //取消报名了
                            text="取消报名了"+order.getVehModel()+"的"+order.getSerType();
                            //取消报名的积分，取消报名的理由

                        }
                        MessageVo mv=new MessageVo(ei.getTechnicianId(),technicianInfo.getImageurl(),technicianInfo.getName(),technicianInfo.getScore()+"",order.getId(),order.getVehPicl(),text, ei.getRegistrationTime());
                        if(ei.getFlag()==1){
                            mv.setEntryScore("-20");
                            mv.setEntryText("有了别的订单");
                        }
                        list.add(mv);
                    }
                }
            }
            //针对list做排序
            Collections.reverse(list);

            resultBean.setRows(list);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean getCity(String xx, String yy) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            resultBean.setResultDesc(TranslateUtil.getAddr(xx,yy));
        }catch (Exception e){

        }
        return resultBean;
    }

    public ResultBean myRecord(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            TechnicianInfo technicianInfo = repository.findById(id);
            RecordVo vo = new RecordVo();
            //头像
            vo.setInfoImageUrl(technicianInfo.getImageurl());
            //等级
            vo.setLevel(technicianInfo.getLevel());
            //综合评分
            vo.setScore(technicianInfo.getScore());

            RecordOrderVo recordOrderVo = new RecordOrderVo();
            List<AcceptInfo> list = acceptInfoRepository.findByTechIdAndFlagOrderByCreateTimeDesc(id,2);//已完成
            List<RecordOrderVo> voList = new ArrayList<>();
            for (AcceptInfo acceptInfo:list){
                OrderList orderList = orderListRepository.findById(acceptInfo.getOrderId());
                EvaluateInfo evaluateInfo = evaluateInfoRepository.findByOrderId(acceptInfo.getOrderId());
                recordOrderVo.setOrderId(acceptInfo.getOrderId());
                recordOrderVo.setStoreName(orderList.getStoreName());
                recordOrderVo.setSerType(orderList.getSerType());
                recordOrderVo.setEndTime(orderList.getEndTime());
                recordOrderVo.setScore(evaluateInfo.getScore());
                recordOrderVo.setContent(evaluateInfo.getCommentContent());
                voList.add(recordOrderVo);
            }
            resultBean.setObject(vo);
            resultBean.setRows(voList);

        }catch (Exception e){
            resultBean.setResultDesc(ResultBean.FAIL);
        }

        return resultBean;
    }

    public ResultBean myCenter(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            TechnicianInfo technicianInfo = repository.findById(id);
            TechInfoVo vo = new TechInfoVo();
            //技师姓名
            vo.setName(technicianInfo.getName());
            //头像
            vo.setInfoImageUrl(technicianInfo.getImageurl());
            //累计赏金
            vo.setSumMoney(technicianInfo.getSumMoney());
            //电话
            vo.setPhone(technicianInfo.getPhone());
            //年龄
            vo.setAge(technicianInfo.getAge());
            //地址
            vo.setAddress(technicianInfo.getCity().concat(technicianInfo.getArea()));

            List<AcceptInfo> list = acceptInfoRepository.findByTechIdAndFlagOrderByCreateTimeDesc(id,2);//已完成
            //订单已完成数量
            vo.setNum(list.size());
            AcceptInfo acceptInfo = list.get(0);
            OrderList orderList = orderListRepository.findById(acceptInfo.getOrderId());
            AcceptInfoVo acceptInfoVo = new AcceptInfoVo();
            acceptInfoVo.setId(orderList.getId());
            acceptInfoVo.setMoney(orderList.getMoney());
            acceptInfoVo.setSerType(orderList.getSerType());
            acceptInfoVo.setPreTime(orderList.getPreTime());
            acceptInfoVo.setPic1(orderList.getVehPicl());
            acceptInfoVo.setStoreName(orderList.getStoreName());
            vo.setAcceptInfoVo(acceptInfoVo);
            resultBean.setObject(vo);
        }catch (Exception e){
            resultBean.setResultDesc(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean techById(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            TechnicianInfo technicianInfo = repository.findById(id);
            TechInfoVo vo = new TechInfoVo();
            //技师姓名
            vo.setName(technicianInfo.getName());
            //头像
            vo.setInfoImageUrl(technicianInfo.getImageurl());
            //电话
            vo.setPhone(technicianInfo.getPhone());
            //年龄
            vo.setAge(technicianInfo.getAge());
            //地址
            vo.setAddress(technicianInfo.getCity().concat(technicianInfo.getArea()));

            resultBean.setObject(vo);
        }catch (Exception e){

        }
        return resultBean;
    }



//    public ResultBean findById(String id) {
//        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
//        try {
//            //1先根据id查找到技师的相关信息
//            TechInfoVo vo = new TechInfoVo();
//            TechnicianInfo f = repository.findById(id);
//            vo.setName(f.getName());
//            vo.setInfoImageUrl(f.getImageurl());
//            //2查找到该技师最后一次的订单任务
//            List<AcceptInfo> list = acceptInfoRepository.findByTechIDOrderByAcceptTimeDesc(id);
//            if (list != null && list.size() > 0) {
//                //3根据订单的id查找到订单的详细信息
//                OrderList orderList = orderListRepository.findById(list.get(0).getOrderID());
//                vo.setDetail(orderList.getDetRequirement());
//            }
//            resultBean.setObject(vo);
//        }catch (Exception e){
//           resultBean.setResultCode(ResultBean.FAIL);
//        }
//        return  resultBean;
//
//    }

}
